import axios1 from 'axios'
import to from '@/utils/awaitTo'
import store from '@/store'
import Notify from '@/ui/Notify'
import router from '@/router'
import { removeStorage } from '@/storage'
// import jsonBig from 'json-bigint'
// axios.defaults.baseURL = 'http://toutiao-app.itheima.net'
var JSONbigString = require('json-bigint')({ storeAsString: true })
const axios = axios1.create({
  baseURL: 'http://toutiao-app.itheima.net',
  transformResponse: [function (data) {
    // jsonBig.parse来转换JSON字符串，遇到大数会转成BigNumber类型
    return JSONbigString.parse(data)
  }]
})

// 添加拦截器
axios.interceptors.request.use(function (config) {
  // 统一添加了Authorization头-携带了身份标识
  if (store.state.token) {
    config.headers.Authorization = 'Bearer ' + store.state.token
  }
  return config
}, function (error) {
  return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(function (response) {
  // response就是响应对象
  return response
}, function (error) {
  if (error.response.status === 401) {
    Notify({ type: 'danger', message: 'token过期-请重新登录' })
    removeStorage('token')
    store.commit('clearToken')
    setTimeout(() => {
      router.push({
        name: 'Login'
      })
    }, 1000)
  }
  return Promise.reject(error)
})
export default ({ url, method = 'GET', data = {}, headers = {}, params = {} }) => {
  const PromiseA = axios({
    url,
    method,
    data,
    headers,
    params
  })
  return to(PromiseA)
}
